import React from 'react';
import { Alert, Image, StyleSheet, Text, TouchableOpacity, View } from 'react-native';
import { NavigationProp, RouteProp } from '@react-navigation/native';
import { CommonStyle } from '../../../common/commonStyle.ts';
import { useSafeAreaInsets } from 'react-native-safe-area-context';
import { ListItem } from '@rneui/base';
import MaterialIcons from 'react-native-vector-icons/MaterialIcons';
import FontAwesome from 'react-native-vector-icons/FontAwesome';
import { useAsyncEffect } from 'ahooks';
import StorageUtil from '../../../utils/Storage.ts';
import { useDispatch, useSelector } from 'react-redux';
import { AppDispatch, RootState } from '../../../redux/store.ts';
import { fetchInitialUserInfo } from '../../../redux/reducers/app.ts';
import Tools from '../../../utils/Tools.ts';
import { LinearGradient } from 'react-native-linear-gradient';
import { Touchable } from 'react-native-toast-message/lib/src/components/Touchable';
import AntDesign from 'react-native-vector-icons/AntDesign';

interface IUserScreenProps {
  navigation: NavigationProp<any, 'user'>;
  route: RouteProp<any, 'user'>;
}

const UserScreen: React.FC<IUserScreenProps> = ({ navigation, route }) => {
  const insets = useSafeAreaInsets();
  const userInfo = useSelector((state: RootState) => state.userInfo);
  const dispatch = useDispatch<AppDispatch>();

  useAsyncEffect(async () => {
    dispatch(fetchInitialUserInfo());
  }, []);

  /**
   * 退出登录
   * @constructor
   */
  const handleLogOutLogIn = () => {
    Alert.alert(
      '',
      '确定要退出?',
      [
        {
          text: '确定',
          onPress: async () => {
            await StorageUtil.remove('token');
            await StorageUtil.remove('userInfo');
            navigation.navigate('login');
          },
        },
        {
          text: '取消',
          onPress: () => {},
          style: 'cancel',
        },
      ],
      { cancelable: true },
    );
  };

  /**
   * 前往屏幕界面
   * @param screen
   * @param extra
   */
  const handleGotoScreen = (screen: string, extra?: object) => {
    navigation.navigate(screen, extra || {});
  };

  /**
   * 渲染头部
   */
  const renderInfo = () => {
    const styles = StyleSheet.create({
      avatarLayout: { width: '100%', flexDirection: 'row', paddingLeft: 16, height: 180, paddingTop: insets.top + 30 },
      avatarImg: { width: 70, height: 70, borderRadius: 10 },
      nameLayout: { marginLeft: 21, marginTop: 10 },
      nicknameText: { fontSize: 15, color: CommonStyle.fontColor, fontWeight: 'bold' },
      idLayout: { flexDirection: 'row', alignItems: 'center', marginTop: 10 },
      idText: { fontSize: 11, color: CommonStyle.deepGrey, paddingRight: 2 },
      functionBar: { width: '95%', backgroundColor: 'white', paddingHorizontal: 5, marginTop: -30, marginBottom: 10, borderRadius: 8, flexDirection: 'row', flexWrap: 'wrap' },
      functionBarItem: { width: '20%', justifyContent: 'center', flexDirection: 'column', paddingVertical: 12 },
      functionBarItemImage: { width: 45, height: 45, margin: 'auto' },
      functionBarItemText: { fontSize: 12, marginTop: 5, textAlign: 'center' },
    });
    return (
      <>
        <LinearGradient start={{ x: 0, y: 0 }} end={{ x: 1, y: 0 }} colors={['#b7dd98', '#81d2bf', '#4cc6e6']} style={styles.avatarLayout}>
          <Image style={styles.avatarImg} source={{ uri: userInfo.imageUrl || 'https://pic.kanglailab.com/common/wuser_logo.png' }} />
          <View style={styles.nameLayout}>
            <Text style={styles.nicknameText}>{userInfo.nickName}</Text>
            <View style={styles.idLayout}>
              <Text style={styles.idText}>{Tools.ProtectingPhoneNumbers(userInfo.phone)}</Text>
            </View>
          </View>
        </LinearGradient>
        <View style={styles.functionBar}>
          <Touchable style={styles.functionBarItem} onPress={() => navigation.navigate('personInfoScreen')}>
            <Image style={styles.functionBarItemImage} resizeMode="cover" source={require('../../../assets/images/user/person-info.png')} />
            <Text style={styles.functionBarItemText}>个人信息</Text>
          </Touchable>
          <View style={styles.functionBarItem}>
            <Image style={styles.functionBarItemImage} resizeMode="cover" source={require('../../../assets/images/user/monthly.png')} />
            <Text style={styles.functionBarItemText}>未结账单</Text>
          </View>
          <Touchable style={styles.functionBarItem} onPress={() => navigation.navigate('memberBalance')}>
            <Image style={styles.functionBarItemImage} resizeMode="cover" source={require('../../../assets/images/user/member-balance.png')} />
            <Text style={styles.functionBarItemText}>会员余额</Text>
          </Touchable>
          <Touchable style={styles.functionBarItem} onPress={() => navigation.navigate('webViewScreen', { title: '社区管理', uri: 'https://kics.kanglailab.com/home', params: { userId: userInfo.userId } })}>
            <Image style={styles.functionBarItemImage} resizeMode="cover" source={require('../../../assets/images/user/communityManagement.png')} />
            <Text style={styles.functionBarItemText}>社区管理</Text>
          </Touchable>
          <Touchable style={styles.functionBarItem} onPress={() => navigation.navigate('pointsManagement')}>
            <Image style={styles.functionBarItemImage} resizeMode="cover" source={require('../../../assets/images/user/integral.png')} />
            <Text style={styles.functionBarItemText}>积分管理</Text>
          </Touchable>
        </View>
      </>
    );
  };

  /**
   * 渲染功能list
   */
  const functionList = () => {
    const styles = StyleSheet.create({
      root: { width: '100%', marginTop: 2 },
      text: {
        fontSize: 14,
        fontWeight: 'bold',
      },
    });
    return (
      <>
        <TouchableOpacity style={styles.root}>
          <ListItem style={styles.root} onPress={() => handleGotoScreen('accountInformationScreen')}>
            <MaterialIcons name="manage-accounts" size={22} color={CommonStyle.mainColor} />
            <ListItem.Content>
              <ListItem.Title style={styles.text}>编辑资料</ListItem.Title>
            </ListItem.Content>
            <ListItem.Chevron />
          </ListItem>
        </TouchableOpacity>
        <TouchableOpacity style={styles.root}>
          <ListItem style={styles.root} onPress={() => Tools.callPhone('4001512686')}>
            <AntDesign name="customerservice" size={22} color={CommonStyle.mainColor} />
            <ListItem.Content>
              <ListItem.Title style={styles.text}>咨询客服</ListItem.Title>
            </ListItem.Content>
            <ListItem.Chevron />
          </ListItem>
        </TouchableOpacity>
        <TouchableOpacity style={styles.root}>
          <ListItem style={styles.root} onPress={() => handleGotoScreen('receivingAddress')}>
            <MaterialIcons name="manage-accounts" size={22} color={CommonStyle.mainColor} />
            <ListItem.Content>
              <ListItem.Title style={styles.text}>收货地址</ListItem.Title>
            </ListItem.Content>
            <ListItem.Chevron />
          </ListItem>
        </TouchableOpacity>
        <TouchableOpacity style={styles.root}>
          <ListItem style={styles.root} onPress={() => handleGotoScreen('emergencyContact')}>
            <FontAwesome name="address-book" size={22} color={CommonStyle.mainColor} />
            <ListItem.Content>
              <ListItem.Title style={styles.text}>紧急联系人</ListItem.Title>
            </ListItem.Content>
            <ListItem.Chevron />
          </ListItem>
        </TouchableOpacity>
      </>
    );
  };
  return (
    <>
      <View style={[styles.root]}>
        {renderInfo()}

        {functionList()}
        <TouchableOpacity style={styles.logOutLogIn} onPress={handleLogOutLogIn}>
          <Text style={{ color: 'red' }}>退出登录</Text>
        </TouchableOpacity>
      </View>
    </>
  );
};

const styles = StyleSheet.create({
  root: { flex: 1, alignItems: 'center' },
  logOutLogIn: { width: '100%', backgroundColor: 'white', marginTop: 10, textAlign: 'center', height: 48, justifyContent: 'center', alignItems: 'center' },
});

export default UserScreen;
